package com.devops.controller;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author: mis_wu
 * @Company: asia info
 * @Create_time: 2023-11-27
 * @Description: 自定义描述
 */
public class ChatGptTest {

    public static void main(String[] args) throws Exception {
        String url = "https://api.openai.com/v1/engines/davinci-codex/completions";
        String apiKey = "Lwc123456789";
        String prompt = "Write a Java program that prints the current date and time.";
        int maxTokens = 50;
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // Set request method
        con.setRequestMethod("POST");
        // Set request headers
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "Bearer " + apiKey);
        // Build request body
        String requestBody = "{\"prompt\": \"" + prompt + "\", \"max_tokens\": " + maxTokens + ", \"temperature\": 0.7}";
        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(requestBody);
        wr.flush();
        wr.close();
        // Get response code
        int responseCode = con.getResponseCode();
        // Read response body
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer responseBuffer = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            responseBuffer.append(inputLine);
        }
        in.close();

        String responseBody = responseBuffer.toString();

        if(responseCode == 200){
            System.out.println(responseBody);
            // Parse the JSON response to get the generated text
            // ...

        } else{
            System.out.println("Error: " + responseBody);
        }
    }
}
